﻿using System;
using WxOpenPLatCore.DBContext;
using WxOpenPLatCore.Interfaces;
using WxOpenPLatCore.Models;
using WxOpenPlatLibCore;

namespace WxOpenPLatCore.Services
{
    public class AdminService : IService
    {
        public Admin Login(string username, string password)
        {
            Admin model = DbSqlHelper.GetEntity<Admin>("select * from open_admin where loginName=@loginName", new MySql.Data.MySqlClient.MySqlParameter[] { new MySql.Data.MySqlClient.MySqlParameter() { ParameterName = "@loginName", Value = username } });
            if (model != null && Cryptography.GetMD5(password, model.loginSalt) == model.loginPwd)
            {
                model.LoginToken = Guid.NewGuid().ToString().Replace("-", "");
                model.logintimes = model.logintimes + 1;
                model.loginDate = DateTime.Now;
                DbSqlHelper.ExecuteNonQuery("update open_admin set LoginToken=@LoginToken,logintimes=@logintimes,loginDate=@loginDate"
                    , new MySql.Data.MySqlClient.MySqlParameter[] {
                        new MySql.Data.MySqlClient.MySqlParameter() { ParameterName = "@logintoken", Value = model.LoginToken },
                        new MySql.Data.MySqlClient.MySqlParameter() { ParameterName = "@logintimes", Value = model.logintimes },
                        new MySql.Data.MySqlClient.MySqlParameter() { ParameterName = "@loginDate", Value = model.loginDate }
                    });
                return model;
            }
            return null;
        }

        public Admin GetByToken(string logintoken)
        {
            Admin model = DbSqlHelper.GetEntity<Admin>("select * from open_admin where logintoken=@logintoken", new MySql.Data.MySqlClient.MySqlParameter[] { new MySql.Data.MySqlClient.MySqlParameter() { ParameterName = "@logintoken", Value = logintoken } });
            return model;
        }
    }
}
